<template>
<!-- 供应商-供应商列表 -->
  <div>
    <Card :bordered="false" dis-hover class="ivu-mt" :padding="0">
      <Form
        inline
        class="formValidate mt20"
        :label-width="80"
        @submit.native.prevent
      >
        <FormItem label="搜索：" label-for="store_name">
          <Input
            placeholder="请输入公司名称"
            v-model="formValidate.company"
           class="input-add"
          />
		  <Input
		    placeholder="请输入手机号"
		    v-model="formValidate.phone"
		   class="input-add"
		  />
          <Button type="primary" @click="getSupplier()">查询</Button>
        </FormItem>
      </Form>
    </Card>

    <Card :bordered="false" dis-hover class="ivu-mt">
      <!-- 操作 -->
      <!-- <Button type="primary" class="btn" @click="addSupplier"
        >添加客户资料</Button
      > -->
      <!-- 表格 -->
      <Table
        :columns="columns"
        :data="tabList"
        ref="table"
        highlight-row
		max-height="580"
        no-data-text="暂无数据"
        no-filtered-data-text="暂无筛选结果"
        class="orderData ivu-mt"
      >
        <!-- 状态 -->
        <template slot-scope="{ row, index }" slot="is_show">
          <i-switch
            v-model="row.is_show"
            @on-change="onchangeIsShow(row)"
            :true-value="1"
            :false-value="0"
            size="large"
          >
            <span slot="open">开启</span>
            <span slot="close">关闭</span>
          </i-switch>
        </template>

        <!-- 操作 -->
        <template slot-scope="{ row, index }" slot="action">

          <!-- <Divider type="vertical" />
          <a @click="edit(row)">编辑</a>
          <Divider type="vertical" /> -->
		  <a type="primary" @click="showFollowUpDetail(row)">查看跟进</a>
			<!-- <Divider type="vertical" />
          <a @click="del(row, '删除客户资料', index)" class="del">删除</a> -->
        </template>
        <!-- no-data-text="暂无数据" highlight-row -->
        <!-- no-filtered-data-text="暂无筛选结果" -->
      </Table>
      <div>
        <!-- 分页 -->
        <div class="acea-row row-right page">
          <Page
            :total="page.total"
            :current="page.pageNum"
            show-elevator
            show-total
            @on-change="pageChange"
            :page-size="page.pageSize"
            @on-page-size-change="limitChange"
          />
        </div>
      </div>
    </Card>
    <menus-from :formValidate="formValidate" ref="menusFrom"></menus-from>
	
	<Modal v-model="followUpModalVisible" title="跟进信息" :footer-hide="true" width="800">
		<div class="article-manager video-icon form-submit" id="shopp-manager">
			<Card :bordered="false" dis-hover class="ivu-mt">
				<Form class="formValidate" ref="formValidate" :model="formData"
					:label-position="labelPosition" @submit.native.prevent>
					<Col span="24">
					<FormItem label="跟进人：" prop="supplier_name">
						<Input v-model="formData.supplier_name" :disabled="true" v-width="460" />
					</FormItem>
					</Col>
	
					<Col span="24">
					<FormItem label="跟进状态：" prop="status">
						<Select v-model="formData.status" v-width="460">
							<Option :value="1">合作</Option>
							<Option :value="2">签约中</Option>
							<Option :value="3">有意向</Option>
							<Option :value="4">无意向</Option>
						</Select>
					</FormItem>
					</Col>
					<Col span="24">
					<FormItem label="跟进信息：" prop="follow_up_info">
						<div v-for="(item, index) in formData.follow_up_info" :key="index"
							style="margin-bottom: 8px;margin-left: 70px;">
							<div class="follow-header">
								<span class="follow-time-label">跟进时间：</span>
								<span class="follow-time-value">
									{{ formatTime(item.time)  || '保存后自动生成' }}
								</span>
							</div>
	
							<div style="display: flex;">
								<Input type="textarea" v-model="item.content" placeholder="请输入跟进信息"
									:autosize="{ minRows: 2, maxRows: 4 }" class="follow-content" />
								<Button type="error" icon="md-remove" @click="removeFollowUp(index)"
									style="margin-left: 8px;" v-if="formData.follow_up_info.length > 1" />
							</div>
	
						</div>
						<Button type="dashed" icon="md-add" @click="addFollowUp"
							style="margin-left: 70px;">添加跟进信息</Button>
					</FormItem>
					</Col>
				</Form>
			</Card>
			<Card :bordered="false" dis-hover>
				<Form>
					<FormItem>
						<div class="floatRight">
							<Button type="primary" class="submission" @click="handleCancel()">取消</Button>
							<div style="display: inline-block;width: 15px;"></div>
							<Button type="primary" class="submission"
								@click="handleSubmit('formValidate')">保存</Button>
						</div>
					</FormItem>
				</Form>
			</Card>
		</div>
	</Modal>
  </div>
</template>
<script>
import { mapState } from 'vuex'
import util from '@/libs/util'
import Setting from '@/setting'
import { 
customerInformationListApi, 
putSupplierStatus, 
supplierLogin,
getCustomerInformation,
createCustomerInformationApi,
createCustomerInformationFollowApi ,
} from '@/api/supplier'
import Template from '../../setting/devise/template.vue'
export default {
  name: '',
  components: {Template },
  props: {},
  data() {
    return {
		followUpModalVisible: false,
		followUpData: {}, // 传入的整条数据
      roterPre: Setting.roterPre,
      keywords: '',
      BaseURL: '',
	  formData:{
		id:0,
		supplier_name:'',
		follow_up_time:'',
		page_type:"opensea",
		status:'',
		follow_up_info: [
		    { content: '', time: '' } // 修改为对象数组，包含内容和时间
		],
	  },
      formValidate: {
        status: '',
        extract_type: '',
		type:2,
		phone:"",
		company:"",
        nireid: '',
        data: 'thirtyday',
        page: 1,
        limit: 20,
      },
      loading: false,
      page: {
        total: 0, // 总条数
        pageNum: 1, // 当前页
        pageSize: 15, // 每页显示条数
      },
      columns: [
        {
          title: 'ID',
          key: 'id',
          minWidth: 80,
        },
        // {
        //   title: '招商员',
        //   minWidth: 100,
        //   key: 'merchants',
        // },
        {
          title: '公司名称',
          key: 'company_name',
          minWidth: 150,
        },
        {
          title: '公司名称(英)',
          key: 'company_name_en',
          minWidth: 100,
        },
        {
          title: '联系人',
          key: 'contacts',
          minWidth: 100,
        },
        {
          title: '联系人电话',
          key: 'phone',
          minWidth: 100,
        },
        {
          title: '联系人邮箱',
          key: 'email',
          minWidth: 100,
        },
        {
          title: '国家地区',
          key: 'address',
          minWidth: 100,
        },
		{
		  title: '主营产品',
		  key: 'product',
		  minWidth: 100,
		},
		{
		  title: '微信群ID',
		  key: 'wx',
		  minWidth: 100,
		},
		{
		  title: '跟进状态',
		  key: 'status',
		  minWidth: 100,
		},
        {
          title: '操作',
          slot: 'action',
          minWidth: 150,
        },
      ],
      tabList: [],
    }
  },
  computed: {
    ...mapState('admin/layout', ['isMobile']),
    labelWidth() {
      return this.isMobile ? undefined : 80
    },
    labelPosition() {
      return this.isMobile ? 'top' : 'right'
    },
  },
  watch: {},
  created() {
    this.getSupplier()
  },
  mounted() {},
  methods: {
	  formatTime(val) {
	  	if (!val) return '保存后自动生成'
	  	const d = new Date(val)
	  	const year = d.getFullYear()
	  	const month = ('0' + (d.getMonth() + 1)).slice(-2)
	  	const day = ('0' + d.getDate()).slice(-2)
	  	const hour = ('0' + d.getHours()).slice(-2)
	  	const minute = ('0' + d.getMinutes()).slice(-2)
	  	return `${year}-${month}-${day} ${hour}:${minute}`
	  },
	  handleCancel(){
		  this.formData = {
		        id: 0,
		        supplier_name: '',
		        status: '',
		        follow_up_info: [{ content: '', time: '' }], // 重置为对象数组
		    }
		  this.followUpModalVisible = false;
	  },
		addFollowUp() {
	      this.formData.follow_up_info.push({ 
	        content: '', 
	        time: '' 
	      });
	    },
	  removeFollowUp(index) {
	      this.formData.follow_up_info.splice(index, 1);
	  },  
	 //  handleSubmit() {
		// this.followUpModalVisible = false;
	 //    if (this.formData.id) {
	 //      createCustomerInformationApi(this.formData.id,this.formData)
	 //        .then(async (res) => {
	 //            this.$Message.success("保存成功")
				
		// 		this.$router.push({ path: this.roterPre + '/supplier/customer-information/list' })
	 //        })
	 //        .catch((res) => {
	 //          this.$Message.error(res.msg)
	 //        })
	 //    }
	 //  },
	  handleSubmit() {
	  	this.followUpModalVisible = false;
		this.formData.page_type = "opensea"
		console.log("this.formData",this.formData)
	  	if (this.formData.id) {
	  		createCustomerInformationFollowApi(this.formData.id, this.formData)
	  			.then(async (res) => {
	  				this.$Message.success("保存成功")
	  				this.$router.push({
	  					path: this.roterPre + '/supplier/customer-information/list'
	  				})
	  				this.getSupplier()
	  			})
	  			.catch((res) => {
	  				this.$Message.error(res.msg)
	  			})
	  	}
	  },
	  // 弹窗触发
	    showFollowUpDetail(row) {
	      this.followUpData = row;
	      this.followUpModalVisible = true;
		  this.findRecord(row);
	    },
	  findRecord(row){
		getCustomerInformation(row.id)
		  .then(async (res) => {
		  this.formData = res.data.info
				let info = res.data.info
				this.formData = info
				if(info.follow_up_info == null){
					this.formData.follow_up_info = []
				}
		  })
		  .catch((res) => {
		    this.$Message.error(res.msg)
		  })  
	  },
	    // 时间格式化函数
	    formatFollowUpTime(time) {
	      if (!time) return '无';
	      const date = new Date(time);
	      const y = date.getFullYear();
	      const m = ('0' + (date.getMonth() + 1)).slice(-2);
	      const d = ('0' + date.getDate()).slice(-2);
	      const h = ('0' + date.getHours()).slice(-2);
	      const i = ('0' + date.getMinutes()).slice(-2);
	      return `${y}-${m}-${d} ${h}:${i}`;
	    },
	  
	    // 根据 follow_up_person id 获取人名（你可以替换为接口映射）
	    getFollowUpPersonName(id) {
	      const map = {
	        1: '张三',
	        2: '李四',
	        0: '系统自动' // 示例用
	      };
	      return map[id] || '未知';
	    },
    // 编辑展位
    editWarehouseExhibition(row) {
      this.$refs.menusFrom.modals = true;
      this.$refs.menusFrom.titleFrom = "编辑展位";
      this.formValidate = row;
    },
    addSupplier() {
      this.$router.push({ path: this.roterPre + '/supplier/customerInformationAdd' })
    },
    getSupplierAgreement(row) {
      this.$router.push({ path: this.roterPre + '/supplier/supplierAgreement/List/' + row.id  })
    },

    pageChange(index) {
      this.page.pageNum = index
      this.getSupplier()
    },

    limitChange(limit) {
      this.page.pageSize = limit
      this.getSupplier()
    },

    // 获取供应商列表
    getSupplier() {
      let data = {
        company_name: this.formValidate.company,
		phone: this.formValidate.phone,
		type:this.formValidate.type,
        page: this.page.pageNum, // 当前页
        limit: this.page.pageSize, // 每页显示条数
      }
      customerInformationListApi(data)
        .then(async (res) => {
          this.tabList = res.data.list
          this.page.total = res.data.count
        })
        .catch((res) => {
          this.$Message.error(res.msg)
        })
    },

    // 编辑
    edit(row) {
      this.$router.push({ path: this.roterPre + '/supplier/customerInformationAdd/' + row.id })
    },

    // 修改状态
    onchangeIsShow(row) {
      putSupplierStatus(row.id, row.is_show)
        .then(async (res) => {
          this.$Message.success(res.msg)
        })
        .catch((res) => {
          this.$$Message.error(res.msg)
        })
    },

    // 进入供应商
    goSupplier(row) {
      supplierLogin(row.id)
        .then(async (res) => {
          let data = res.data
          let expires = data.expires_time
          util.cookies.setSupplier('token', data.token, {
            expires: expires,
          })
          util.cookies.setSupplier('uuid', data.user_info.id, {
            expires: expires,
          })
          util.cookies.setSupplier('expires_time', expires, {
            expires: expires,
          })
		  util.cookies.setSupplier('pageTitle', row.supplier_name);
          util.makeMenu(`/${data.prefix}`, data.menus)
          let storage = window.localStorage
          storage.setItem('menuListSupplier', JSON.stringify(data.menus))
          storage.setItem(
            'uniqueAuthSupplier',
            JSON.stringify(data.unique_auth)
          )
          let userInfoSupplier = {
            account: data.user_info.account,
            head_pic: data.user_info.avatar,
            logo: data.logo,
            logoSmall: data.logo_square,
            version: data.version,
          }
          storage.setItem('userInfoSupplier', JSON.stringify(userInfoSupplier))
          this.BaseURL = Setting.apiBaseURL.replace(/adminapi/, `${row.prefix}/home/`);
          window.open(this.BaseURL)
        })
        .catch((res) => {
          this.$Message.error(res.msg)
        })
    },

    // 删除
    del(row, tit, num) {
      let data = {
        ids: row.id,
      }
      let delfromData = {
        title: tit,
        num: 0,
        url: `/supplier/deleteCustomerInformation`,
        method: 'DELETE',
        ids: data,
      }
      this.$modalSure(delfromData)
        .then((res) => {
          this.$Message.success(res.msg)
          this.tabList.splice(num, 1);
          if (!this.tabList.length) {
            this.page.pageNum =
                this.page.pageNum == 1 ? 1 : this.page.pageNum - 1;
          }
          this.getSupplier()
        })
        .catch((res) => {
          this.$Message.error(res.msg)
        })
    },
  },
}
</script>
<style scoped lang="less">
.input-add {
 width: 250px;
 margin-right: 14px
}
.btn {
  margin: 0 0 10px 0px;
}
.del {
  margin-left: 10px;
}
// .card {
//   margin-top: 15px;
// }
.ivu-form-inline {
  padding-top: 20px;
}
.follow_content{
	white-space: pre-line;
	    border-radius: 6px;
	    background: #ffffff;
	    padding: 16px 20px;
	    border: 1px solid #e5e5e5;
	    box-shadow: inset 0 1px 3px rgba(0,0,0,0.05);
	    font-size: 14px;
	    color: #333;
	    line-height: 1.7;
	    max-height: 300px;
	    overflow-y: auto;
}
.floatRight{
	float:right
}
/* 添加样式 */
.follow-item {
  margin-bottom: 16px;
  padding: 12px;
  border: 1px solid #dcdee2;
  border-radius: 4px;
  position: relative;
}

.follow-header {
  margin-bottom: 8px;
  color: #808695;
  font-size: 12px;
}

.follow-content {
  width: 100% !important;
}

.follow-remove-btn {
  position: absolute;
  top: 10px;
  right: 10px;
}

.add-follow-btn {
  margin-top: 8px;
}
</style>